// 教师服务类
package org.example.backend.service;

import org.example.backend.dto.TeacherDto;
import org.example.backend.entity.Student;
import org.example.backend.entity.Teacher;
import org.example.backend.entity.User;
import org.example.backend.exception.BusinessException;
import org.example.backend.exception.ResourceNotFoundException;
import org.example.backend.repository.StudentRepository;
import org.example.backend.repository.TeacherRepository;
import org.example.backend.repository.UserRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class TeacherService {

    private final TeacherRepository teacherRepository;
    private final UserRepository userRepository;
    private final StudentRepository studentRepository;

    public TeacherService(TeacherRepository teacherRepository, UserRepository userRepository,
                          StudentRepository studentRepository) {
        this.teacherRepository = teacherRepository;
        this.userRepository = userRepository;
        this.studentRepository = studentRepository;
    }

    /**
     * 创建教师信息
     */
    public Teacher createTeacher(TeacherDto teacherDto, Long userId) {
        // 检查教师工号是否已存在
        if (teacherRepository.findByTeacherNumber(teacherDto.getTeacherNumber()).isPresent()) {
            throw new BusinessException("教师工号已存在");
        }

        // 检查用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));

        // 检查是否已有关联的教师信息
        if (teacherRepository.findByUserId(userId).isPresent()) {
            throw new BusinessException("该用户已有关联的教师信息");
        }

        Teacher teacher = new Teacher();
        teacher.setUserId(userId);
        teacher.setTeacherNumber(teacherDto.getTeacherNumber());
        teacher.setName(teacherDto.getName());
        teacher.setGender(teacherDto.getGender());
        teacher.setTitle(teacherDto.getTitle());
        teacher.setDepartment(teacherDto.getDepartment());
        teacher.setAvatar(teacherDto.getAvatar());

        return teacherRepository.save(teacher);
    }

    /**
     * 更新教师信息
     */
    public Teacher updateTeacher(Long teacherId, TeacherDto teacherDto) {
        Teacher teacher = teacherRepository.findById(teacherId)
                .orElseThrow(() -> new ResourceNotFoundException("教师信息不存在"));

        // 检查教师工号是否已被其他教师使用
        Teacher existingTeacher = teacherRepository.findByTeacherNumber(teacherDto.getTeacherNumber()).orElse(null);
        if (existingTeacher != null && !existingTeacher.getId().equals(teacherId)) {
            throw new BusinessException("教师工号已存在");
        }

        teacher.setTeacherNumber(teacherDto.getTeacherNumber());
        teacher.setName(teacherDto.getName());
        teacher.setGender(teacherDto.getGender());
        teacher.setTitle(teacherDto.getTitle());
        teacher.setDepartment(teacherDto.getDepartment());
        teacher.setAvatar(teacherDto.getAvatar());

        return teacherRepository.save(teacher);
    }

    /**
     * 获取教师信息
     */
    @Transactional(readOnly = true)
    public Teacher getTeacherByUserId(Long userId) {
        return teacherRepository.findByUserId(userId)
                .orElseThrow(() -> new ResourceNotFoundException("教师信息不存在"));
    }

    /**
     * 获取教师信息
     */
    @Transactional(readOnly = true)
    public Teacher getTeacherById(Long teacherId) {
        return teacherRepository.findById(teacherId)
                .orElseThrow(() -> new ResourceNotFoundException("教师信息不存在"));
    }

    /**
     * 获取指导的学生列表
     */
    @Transactional(readOnly = true)
    public Page<Student> getMyStudents(Long teacherId, int page, int size) {
        Pageable pageable = org.springframework.data.domain.PageRequest.of(page, size);
        return studentRepository.findByTeacherId(teacherId, pageable);
    }

    /**
     * 判断是否是自己指导的学生
     */
    @Transactional(readOnly = true)
    public boolean isMyStudent(Long teacherId, Long studentId) {
        return !studentRepository.existsByTeacherIdAndId(teacherId, studentId);
    }

    /**
     * 管理员更新教师信息
     */
    public Teacher updateTeacherByAdmin(Long userId, TeacherDto teacherDto) {
        Teacher teacher = teacherRepository.findByUserId(userId)
                .orElseThrow(() -> new ResourceNotFoundException("教师信息不存在"));

        // 检查教师工号是否已被其他教师使用
        Teacher existingTeacher = teacherRepository.findByTeacherNumber(teacherDto.getTeacherNumber()).orElse(null);
        if (existingTeacher != null && !existingTeacher.getId().equals(teacher.getId())) {
            throw new BusinessException("教师工号已存在");
        }

        teacher.setTeacherNumber(teacherDto.getTeacherNumber());
        teacher.setName(teacherDto.getName());
        teacher.setGender(teacherDto.getGender());
        teacher.setTitle(teacherDto.getTitle());
        teacher.setDepartment(teacherDto.getDepartment());
        teacher.setAvatar(teacherDto.getAvatar());

        return teacherRepository.save(teacher);
    }

    /**
     * 管理员获取教师列表
     */
    @Transactional(readOnly = true)
    public Page<TeacherDto> getTeachers(String name, String teacherNumber, String department, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        Page<Teacher> teacherPage = teacherRepository.findByConditions(name, teacherNumber, department, pageable);

        return teacherPage.map(teacher -> {
            TeacherDto dto = new TeacherDto();
            dto.setId(teacher.getId());
            dto.setTeacherNumber(teacher.getTeacherNumber());
            dto.setName(teacher.getName());
            dto.setGender(teacher.getGender());
            dto.setTitle(teacher.getTitle());
            dto.setDepartment(teacher.getDepartment());
            dto.setAvatar(teacher.getAvatar());

            // 获取用户信息（邮箱和手机号）
            try {
                User user = userRepository.findById(teacher.getUserId()).orElse(null);
                if (user != null) {
                    dto.setEmail(user.getEmail());
                    dto.setPhone(user.getPhone());
                }
            } catch (Exception e) {
                // 忽略异常
            }

            return dto;
        });
    }

}
